import React, {useEffect, useRef, useState} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {connect} from 'umi';
import {
  getCertificateList,
  getContractModelList,
  getContractSubjectList,
  saveOrUpdateCertificateInfo,
  certificateBpm,
  deleteCertificate
} from './service';
import {Tabs,Button,message,Divider,Popconfirm} from 'antd';
import moment from 'moment';
import AddForm from './components/AddForm';
import { PlusOutlined } from '@ant-design/icons';

const {TabPane} = Tabs;

const TableList = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [contractList, setContractList] = useState([]);
  const [tempContractList,setTempContractList] = useState([]);
  const [contractData, setContractData] = useState([]);

  useEffect(() => {
    getContractModelList().then(res => {
      let temp = res.filter(item => item.name.indexOf('已离职人员模板') > -1);
      setTempContractList(temp);
      setContractList(res);
    });
    //获取合同主体
    getContractSubjectList().then(res => {
      setContractData(res);
    });
  }, []);

  const handleChangTabIndex = (key) => {
    if (key === '1') {
      actionRef.current && actionRef.current.reload();
    } else {
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const addVerify = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveOrUpdateCertificateInfo(values).then((res) => {
        if (res.flag) {
          handleCancel();
          message.success('申请发送成功！');
          actionRef.current.reload();
        } else {
          message.error(`操作失败，错误:` + res.error);
        }
      }
    );
    setLoading(false);
  };

  const sendCertificateBpm = (id) => {
    certificateBpm(id).then(res => {
      if(res.flag){
        message.success('操作成功！');
        window.open(res.data);
        actionRef.current.reload();
      }else{
        message.error(`bpm错误:` + res.error);
      }
    })
  };

  const confirmDelete = (id) => {
    deleteCertificate(id).then(res => {
      if(res.flag){
        message.success('删除成功！');
        actionRef.current.reload();
      }else{
        message.error(res.error);
      }
    });
  };

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true
    },
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '公司',
      dataIndex: 'orgName',
      hideInSearch: true
    },
    {
      title: '部门',
      dataIndex: 'unitName',
      hideInSearch: true
    },
    {
      title: '岗位',
      dataIndex: 'jobName',
      hideInSearch: true
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '证明类型',
      dataIndex: 'modelId',
      hideInSearch: true,
      render: (text) => {
        return contractList.find((item) => item.id === text).name
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      width: '15%',
      render: (item, record) => (
        <>
          {(record.modelName.indexOf('已离职人员模板') > -1) && record.status === '0' ? <>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => confirmDelete(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
            <a onClick={() => sendCertificateBpm(record.id)}>发起</a>
            </> : (record.bpmUrl) && <a onClick={() => window.open(record.bpmUrl)}>审批详情</a>
          }
          {(record.status === '2' && record.contractOssUrl) && <><Divider type="vertical"/><a onClick={() => window.open(record.contractOssUrl)}>下载证明</a></>}
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="1" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="1">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => getCertificateList(params, [0,1])}
            columns={columns}
            toolBarRender={(action, {selectedRows}) => [
              <Button type="primary" onClick={() => addVerify(null)}><PlusOutlined/>新增</Button>
            ]}
          />
        </TabPane>
        <TabPane tab="已办理" key="2">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => getCertificateList(params, [2])}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <AddForm
        loading={loading}
        visible={visible}
        contractList={tempContractList}
        contractData={contractData}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};
export default connect(() => ({}))(TableList)
